package StudyCode.summary.aclfile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class IsTextFileBinary {

	public static void main(String[] args) throws IOException {
		File file = new File("E:/Copy/1.txt");
		System.out.println("文件 " + file + "是文本文件还是二进制文件?" + isText(file));
	}

	private static boolean isText(final File file) throws IOException,
			IllegalArgumentException {
		RandomAccessFile raf = null;

		try {
			raf = new RandomAccessFile(file, "r");
			int numberOfNonTextChars = 0;
			while (raf.getFilePointer() < raf.length()) {
				final int b = raf.readUnsignedByte();
				if (b == 0x09 || // horizontal tabulation
						b == 0x0A || // line feed
						b == 0x0C || // form feed
						b == 0x0D || // carriage return
						(b >= 0x20 && b <= 0x7E) || // "normal" characters
						(b >= 0x80 && b <= 0x9F) || // latin-1 symbols
						(b >= 0xA0 && b <= 0xFF)) // latin-1 symbols
				{
					// OK
				} else {
					numberOfNonTextChars++;
				}
			}
			return numberOfNonTextChars <= 2
					&& (raf.length() - numberOfNonTextChars / raf.length()) >= 0.99;

		} finally {
			raf.close();
		}
	}
}
